/**
 * Copyright 2011 HNB. All rights reserved.
 * HNB PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package my.hnb.android.view.karaoke;

import java.io.File;

import my.hnb.android.common.ActionEvent;
import my.hnb.android.common.AppInfo;
import my.hnb.android.common.ModelEvent;
import my.hnb.android.constant.EventConstant;
import my.hnb.android.constant.IntentConstants;
import my.hnb.android.constant.SharedPref;
import my.hnb.android.controller.UserController;
import my.hnb.android.dto.SongDTO;
import my.hnb.android.dto.SongDetailDTO;
import my.hnb.android.ultils.AppUltils;
import my.hnb.android.ultils.StringUtil;
import my.hnb.android.ultils.download.DownloadFile;
import my.hnb.android.ultils.download.ExternalStorage;
import my.hnb.android.view.base.BaseActivity;
import my.hnb.android.view.common.Splashscreen;
import my.hnb.songnhac.R;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Man hinh chi tiet bai hat
 * 
 * @author BANGHN
 */
public class SongDetailView extends BaseActivity implements OnClickListener {
	// du lieu chi tiet bai hat
	SongDetailDTO songDetail;
	// parent activity
	TextView tvSongCode;
	TextView tvSongName;
	TextView tvSongInfo;
	TextView tvSongLyric;
	TextView tvFavorite;
	CheckBox checkFavorite;
	ImageView ivAd;
	// ma bai hat truyen qua
	String songCode;

	String urlImage;
	String urlAd;
	int indexSelectSong = -1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_song_detail);
		this.setTitleLeftText(StringUtil.getString(R.string.song_detail));
		//tvHeader.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.logo_musiccore_small), null);
		//tvHeader.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.logo_musiccore_small, 0);
		//tvHeader.setCompoundDrawablePadding(AppUltils.dip2Pixel(this, 10));
		ivMenu.setImageResource(R.drawable.logo_musiccore_small);
		ivMenu.setPadding(AppUltils.dip2Pixel(this, 5), 0, AppUltils.dip2Pixel(this, 5), 0);
		
		ivMenu.getLayoutParams().height = AppUltils.dip2Pixel(this, 30);
		ivMenu.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
		
		//ivMenu.setVisibility(View.GONE);
		
		tvSongCode = (TextView) findViewById(R.id.tvSongCode);
		tvSongName = (TextView) findViewById(R.id.tvSongName);
		tvSongInfo = (TextView) findViewById(R.id.tvSongInfo);
		tvSongLyric = (TextView) findViewById(R.id.tvSongLyric);
		tvFavorite = (TextView) findViewById(R.id.tvFavorite);
		checkFavorite = (CheckBox) findViewById(R.id.checkFavorite);
		ivAd = (ImageView) findViewById(R.id.ivAd);
		checkFavorite.setOnClickListener(this);
		ivAd.setOnClickListener(this);

		
		songCode = getIntent().getExtras().getString(IntentConstants.INTENT_SONG_CODE);
		indexSelectSong = getIntent().getExtras().getInt(IntentConstants.INTENT_INDEX);
		SongDTO song = (SongDTO) getIntent().getExtras().getSerializable(IntentConstants.INTENT_DATA);
		if(song != null){
			tvSongCode.setText("" + song.songNumber);
			tvSongName.setText(song.songName);
			if (song.favorite == 1) {
				checkFavorite.setChecked(true);
			} else {
				checkFavorite.setChecked(false);
			}
		}
		requesetGetSongDetail();
		executeShowImageAd();
	}

	private void executeShowImageAd(){
		SharedPreferences sharedPreferences = AppInfo.getInstance().getAppContext().getSharedPreferences(
				Splashscreen.PREFS_PRIVATE, Context.MODE_PRIVATE);
		urlAd  = sharedPreferences.getString(SharedPref.AD_URL, ""); 
		urlImage  = sharedPreferences.getString(SharedPref.AD_IMAGE, ""); 

		File fileDir = ExternalStorage.getAdPath();
		String fileName = StringUtil.md5(urlImage);
		if (!StringUtil.isNullOrEmpty(urlImage)) {
			if(ExternalStorage.isFileExistsInDirectory(fileDir, fileName)){
				showImageAd();
			}else{
				if (AppUltils.checkNetworkAccess())
					new DownloadAdTask().execute(urlImage);
			}
		}
	}
	
	private void showImageAd(){
		File fileDir = ExternalStorage.getAdPath();
		String fileName = StringUtil.md5(urlImage);
		ivAd.setImageBitmap(AppUltils.readImageFromSDCard(fileDir.getAbsolutePath() + "/" + fileName));
		ivAd.setVisibility(View.VISIBLE);
	}
	
	
	@Override
	public void onClick(View view) {
		if (view == checkFavorite) {
			if (checkFavorite.isChecked()) {
				songDetail.favorite = 1;
				tvFavorite.setText(StringUtil.getString(R.string.remove_favorite));
			} else {
				songDetail.favorite = 0;
				tvFavorite.setText(StringUtil.getString(R.string.add_favorite));
			}
			requestUpdateFavorite();
			notifySongFavorite();
		}else if (view == ivAd){
			if (!StringUtil.isNullOrEmpty(urlAd)) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlAd));
				startActivity(browserIntent);
			}
		}
	}

	private void notifySongFavorite(){
		Bundle bundle = new Bundle();
		bundle.putInt(IntentConstants.INTENT_INDEX, indexSelectSong);
		bundle.putLong(IntentConstants.INTENT_SONG_CODE, songDetail.songNumber);
		bundle.putInt(IntentConstants.INTENT_SONG_FAVORITE, songDetail.favorite);
		sendBroadcast(EventConstant.NOTIFY_FAVORITE, bundle);
	}
	
	/**
	 * Cap nhat trang thai bai hat yeu thich
	 * 
	 * @author BANGHN
	 */
	private void requestUpdateFavorite() {
		ActionEvent e = new ActionEvent();
		Bundle b = new Bundle();
		b.putString(IntentConstants.INTENT_SONG_CODE, songCode);
		b.putInt(IntentConstants.INTENT_SONG_FAVORITE, songDetail.favorite);
		e.viewData = b;
		e.action = EventConstant.UPDATE_FAVORITE;
		e.sender = this;
		UserController.getInstance().handleViewEvent(e);
	}

	/**
	 * Request lay danh sach bai nhac
	 * 
	 * @author BANGHN
	 */
	private void requesetGetSongDetail() {
		ActionEvent e = new ActionEvent();
		Bundle b = new Bundle();
		b.putString(IntentConstants.INTENT_SONG_CODE, songCode);
		e.viewData = b;
		e.action = EventConstant.GET_SONG_DETAIL;
		e.sender = this;
		UserController.getInstance().handleViewEvent(e);
	}

	/**
	 * Hien thi thong tin
	 * 
	 * @author BANGHN
	 */
	private void renderLayout() {
		tvSongCode.setText("" + songDetail.songNumber);
		tvSongName.setText(songDetail.songName);
		StringBuffer songInfo = new StringBuffer();
		if(!StringUtil.isNullOrEmpty(songDetail.musican)){
			songInfo.append(songDetail.musican);
		}
		if(!StringUtil.isNullOrEmpty(songDetail.type)){
			songInfo.append(" - " + songDetail.type);
		}
		if(!StringUtil.isNullOrEmpty(songDetail.vol)){
			songInfo.append(" - Vol " + songDetail.vol);
		}
		
		if(StringUtil.isNullOrEmpty(songInfo.toString())){
			tvSongInfo.setVisibility(View.GONE);
		}else{
			tvSongInfo.setText(songInfo.toString());
		}
		
		tvSongLyric.setText(songDetail.fullLyric);
		if (songDetail.favorite == 1) {
			checkFavorite.setChecked(true);
		} else {
			checkFavorite.setChecked(false);
		}
	}

	@Override
	public void handleModelViewEvent(ModelEvent modelEvent) {
		ActionEvent act = modelEvent.getActionEvent();
		switch (act.action) {
		case EventConstant.GET_SONG_DETAIL: {
			songDetail = (SongDetailDTO) modelEvent.getModelData();
			renderLayout();
			closeProgressDialog();
		}
		
		default:
			super.handleModelViewEvent(modelEvent);
			break;
		}
	}

	@Override
	public void handleErrorModelViewEvent(ModelEvent modelEvent) {
		super.handleErrorModelViewEvent(modelEvent);
	}

	
	private class DownloadAdTask extends AsyncTask<String, Void, Exception> {
		@Override
		protected void onPreExecute() {
		}

		@Override
		protected Exception doInBackground(String... params) {
			String url = (String) params[0];
			try {
				downloadAndCacheImage(url);
			} catch (Exception e) {
				e.printStackTrace();
				return e;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Exception result) {
			if (result != null) {
			} else {
				showImageAd();
			}
		}
	}
	
	private static void downloadAndCacheImage(String url){
		File fileDir = ExternalStorage.getAdPath();
		String fileName = StringUtil.md5(url);
		File file = new File(fileDir.getPath() + "/" + fileName);
		try {
			DownloadFile.downloadWithURLConnection(url, file, fileDir);
		} finally {
			//file.delete();
		}
	}
}
